/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package server;

import java.io.*;
import java.net.*;

// Trida obsluhujici kazdeho klienta, ktery se pripoji na server
public class ClientThread extends Thread
{
	private Socket socket;
	// private PrintStream out;
	// private BufferedReader in;
	private BufferedOutputStream bout = null;
	private BufferedInputStream bin = null;
	private String name = "User" + getId();

	public ClientThread(Socket socket)
	{
		this.socket = socket;
		try
		{
			// out = new PrintStream(socket.getOutputStream());
			bout = new BufferedOutputStream(socket.getOutputStream());
			// in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			bin = new BufferedInputStream(socket.getInputStream());
		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			close();
		}
	}

	// Metoda, ktera odesila zpravy vsem klientum
	public synchronized void broadcast(String message, ClientThread from)
	{
		String nick = from.getClientName();
		for (ClientThread clt : Server.getClients())
		{
			// clt.out.println(Sifrovani.encrypt(nick + ": " + message));
			try
			{
				clt.writeData(Sifrovani.encrypt(nick + ": " + message));
			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// Metoda, ktera odesila zpravy vsem klientum
	public synchronized void broadcastChangedClientStatus(ClientThread from, boolean justConnected)
	{
		String nick = from.getClientName();
		for (ClientThread clt : Server.getClients())
		{
			if(clt == from)
				continue;
			try
			{
				if (justConnected)
					clt.writeData(Sifrovani.encrypt(nick + " connected."));
				else
					clt.writeData(Sifrovani.encrypt(nick + " disconnected."));
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	// Metoda slouzici ke cteni zprav
	@Override
	public void run()
	{
		sendPhrase(); // Synchronizace sifrovaciho klice pomoci Vernamovy sifry
		try
		{
			while (!isInterrupted())
			{

				String	message = readData();
				
				if (message == null)
					continue;

				// Pokud je stisknuto tlacitko "disconnect" je klient odpojen
				if (message.contains("ClientControlShutdown"))
					throw new IOException("Shutting down"); 
				else if (message.contains("Nickname"))
				{
					if (!message.equals("NULLNickname"))
						setClientName(message.substring(8));
					broadcastChangedClientStatus(this, true);
				}
				else
					// pokud ne, odesle se zprava klientum
					broadcast(Sifrovani.decrypt(message), this);
				try
				{
					Thread.sleep(100);
				}
				catch (InterruptedException e)
				{
				}
			}
		}
		catch (IOException e)
		{
			broadcastChangedClientStatus(this, false);
			close();
		}
	}

	// Uzavreni socketu a preruseni vlakna, slouzi pri restartu a vypnuti serveru
	public void close()
	{
		try
		{
			bout.close();
			bin.close();
			socket.close();
		}
		catch (IOException e)
		{
		}
		Server.RemoveClient(this);
		interrupt();
	}

	// Synchronizace sifrovaciho klice pomoci Vernamovy sifry
	private void sendPhrase()
	{
		try
		{
			Thread.sleep(100);
			// 1st pass
			String phrase = Sifrovani.getPhrase();
			Vernam v = new Vernam();
			v.setPhrase(phrase);
			v.generateKey();
			writeData(v.XOR());
			Thread.sleep(100);
			// 2nd pass
			String b = readData();
			Thread.sleep(100);
			v.setPhrase(b);
			writeData(v.XOR());
			Thread.sleep(100);
			v.forget();
		}
		catch (IOException e)
		{
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	// Posila data pres sit ke klientovi, pouziva se pouze pro prenos sifrovaciho klice
	private void writeData(String s) throws IOException
	{
		byte[] msg = s.getBytes();
		int len = msg.length + 2;
		bout.write(len & 0xff);
		bout.write(len >> 8 & 0xff);
		bout.write(msg);
		bout.flush();
	}

	// Prijma data pres sit od klienta, pouziva se pouze pro prenos sifrovaciho klice
	private String readData() throws IOException
	{
		int lengthLo = bin.read();
		int lengthHi = bin.read();
		int length = lengthHi * 256 + lengthLo;

		byte[] data = new byte[length - 2];

		int receivedBytes = 0;
		int newBytes = 0;
		int left = length - 2;
		while (newBytes != -1 && receivedBytes < length - 2)
		{
			newBytes = bin.read(data, receivedBytes, left);
			receivedBytes = receivedBytes + newBytes;
			left -= newBytes;
		}

		return new String(data);
	}

	private void setClientName(String name)
	{
		this.name = name;
	}

	public String getClientName()
	{
		return name;
	}
}